package _rabbitmq.community;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Channel;

/**
 * @author huangya
 * @date 2024/9/11
 */
public class ProducerDemo {

    private final static String VIRTUAL_HOST = "/scene_engine_pre";
//    private final static String VIRTUAL_HOST = "/common";
    private final static String EXCHANGE_NAME = "scene_awareness_exchange_pre";
    private final static String ROUTING_KEY = "";

    public static void main(String[] argv) throws Exception {
        // 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        // RabbitMQ 服务器地址
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost(VIRTUAL_HOST);
        Connection connection = null;
        Channel channel = null;
        try {
            // 从连接工厂中获取连接
            connection = factory.newConnection("生产者");
            // 从连接中获取通道channel
            channel = connection.createChannel();
            // 声明一个Fanout交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout", false);

            String message = "{\"vin\":\"xxxx\",\"event_name\":\"test\",\"data\":{\"key\":\"value\"}}";
            // 发布消息到交换机
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("发送消息出现异常...");
        } finally {
            // 7: 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
